package com.example.broadcast_receiver;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;


public class MainActivity extends AppCompatActivity {

    //广播的口令
    public static final String CUSTOM_BROADCAST_ACTION = "com.example.broadcast_receiver.CUSTOM_ACTION";
    private MyDynamicReceiver myReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button sendBroadcastButton = findViewById(R.id.button);

        // 发送广播
        sendBroadcastButton.setOnClickListener(v -> {
            Intent intent = new Intent(CUSTOM_BROADCAST_ACTION);
            // 全局广播接受
            sendBroadcast(intent);
            //本地广播接受
            //LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
        });


     /*   全局广播
        动态注册失败,暂时没有找到原因
        找到原因了:
        对于以Build为 Android14的应用程序版本代码。(SDK高于34的)
        如果接收器没有为系统广播注册，或者将引发SecurityException，
        则必须指定RECEIVER_EXPORTED或RECEIVE_NOT_EXPORTED。
*/

        IntentFilter filter = new IntentFilter();
        filter.addAction(CUSTOM_BROADCAST_ACTION);
        myReceiver = new MyDynamicReceiver();
        registerReceiver(myReceiver, filter, Context.RECEIVER_EXPORTED);


       /* // 动态注册本地广播 应用内广播
        IntentFilter filter = new IntentFilter();
        filter.addAction(CUSTOM_BROADCAST_ACTION);
        myReceiver = new MyDynamicReceiver();
        LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver, filter);

*/
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myReceiver); // 取消注册，防止内存泄漏
    }


}